package com.lw.leetcode.arr.b;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 1546. 和为目标值且不重叠的非空子数组的最大数目
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/30 16:21
 */
public class MaxNonOverlapping {

    public static void main(String[] args) {
        MaxNonOverlapping test = new MaxNonOverlapping();

        // 2
//        int[] arr = {1,1,1,1,1};
//        int k = 2;

        // 2
//        int[] arr = {-1,3,5,1,4,2,-9};
//        int k = 6;

        // 3
//        int[] arr = {-2,6,6,3,5,4,1,2,8};
//        int k = 10;

        // 3
        int[] arr = {0, 0, 0};
        int k = 0;

        int i = test.maxNonOverlapping(arr, k);

        System.out.println(i);
    }

    public int maxNonOverlapping(int[] nums, int target) {
        int length = nums.length;
        for (int i = 1; i < length; i++) {
            nums[i] += nums[i - 1];
        }
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 0);
        int max = 0;
        for (int num : nums) {
            int k = num - target;
            Integer v = map.get(k);
            if (v == null) {
                map.put(num, max);
            } else {
                max = Math.max(max, v + 1);
                map.put(num, max);
            }
        }
        return max;
    }

}
